package com.it.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.it.oss.service.OssService;
import com.it.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {

    public String uploadFileAvatar(MultipartFile file) {

        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;

        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 上传文件输入流。
            InputStream inputStream = file.getInputStream();

            //获取文件名称
            String fileName = file.getOriginalFilename();
            //给文件名加上随机数，防止覆盖
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            fileName=uuid+fileName;

            //上传的文件按照日期分类 使用时间工具类 pom已经配好
            //2020/01/10
            String datePath = new DateTime().toString("yyyy/MM/dd");
            fileName=datePath+"/"+fileName;


            //调用oss方法实现上传
            //bucketName名称   fileName文件名 和文件上传流
            ossClient.putObject(bucketName,fileName, inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();

            //上传后文件路径返回
            //https://edu-1010dcl.oss-cn-beijing.aliyuncs.com/%E5%A4%B4%E5%83%8F.jfif
            String url="https://"+bucketName+"."+endpoint+"/"+fileName;
            return url;

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }
}
